package com.zoo.springbootinit.service.impl;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zoo.springbootinit.common.ErrorCode;
import com.zoo.springbootinit.exception.BusinessException;
import com.zoo.springbootinit.model.entity.Picture;
import com.zoo.springbootinit.service.PictureService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class PictureServiceImpl implements PictureService {
    @Override
    public Page<Picture> searchPicture(String searchText, long pageNum, long pageSize){
        //组织请求参数
        long sequence = (pageNum-1)*pageSize;
        String url = "https://cn.bing.com/images/search?q=" + searchText + "&first=" + sequence;
        Document doc;
        try {
            doc = Jsoup.connect(url).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图片搜索失败");
        }
        //图片和标题所在的div标签
        Elements elements = doc.select(".iuscp.isv");
        List<Picture> pictures = new ArrayList<>();
        for (Element element : elements) {
            //取图片
            String m = element.select(".iusc").attr("m");
            Map<String,Object> map = JSONUtil.toBean(m, Map.class);
            String murl = (String) map.get("murl");
            //取标题
            String title = element.select(".inflnk").attr("aria-label");
            pictures.add(new Picture(title,murl));
            if(pictures.size()>=pageSize){
                break;
            }
        }
         Page<Picture> pagePicture = new Page<>(pageNum,pageSize);
        pagePicture.setRecords(pictures);
        return pagePicture;
    }
}
